//
//  UIScrollView+Direction.m
//  AntFarms
//
//  Created by LF on 2018/1/12.
//  Copyright © 2018年 MuXi. All rights reserved.
//

#import "UIScrollView+Direction.h"
#import <objc/runtime.h>
#import "AppDelegate.h"

@implementation UIScrollView (Direction)





+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    UIScrollView *scr = [super allocWithZone:zone];
    scr.enableDirection = YES;
    return scr;
}

-(void)setDirection:(LFDirection)direction{
    
    objc_setAssociatedObject(self, @selector(direction), @(direction), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (LFDirection)direction{
    
    NSNumber * number = objc_getAssociatedObject(self, @selector(direction));
    return number.integerValue;
}
- (void)setEnableDirection:(BOOL)enableDirection{
    
    objc_setAssociatedObject(self, @selector(enableDirection), @(enableDirection), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    
    if (enableDirection) {
        
//        [self addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
    }
}
- (BOOL)enableDirection{
    
    NSNumber * number = objc_getAssociatedObject(self, _cmd);
    
    return number.integerValue;
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *, id> *)change context:(void *)context {
    if ([change[@"new"] CGPointValue].y > [change[@"old"] CGPointValue].y  ) { // 向上滚动
//        NSLog(@"up");
        self.direction = LFDirectionUp;
        
    } else if ([change[@"new"] CGPointValue].y < [change[@"old"] CGPointValue].y  ) { // 向下滚动
//        NSLog(@"down");
        self.direction = LFDirectionDown;
    }
//    AppDelegate *app = APPDELEGATE;
//    app.redView.hidden = self.direction == LFDirectionUp;
}

//- (void)dealloc {
//    // 移除监听
//    [self removeObserver:self forKeyPath:@"contentOffset"];
//}

@end
